const db = wx.cloud.database()
var app = getApp()
const _ = db.command
Page({
  data: {
    classification: [],
    goodinfo: [],
    class_cur: 1
  },

  onLoad: function (options) {
    db.collection('classification').orderBy('id', 'asc').get().then(res => {
      this.setData({
        classification: res.data
      })
    })
    db.collection('goods').where({
      classification: this.data.class_cur
    }).get().then(res => {
      this.setData({
        goodinfo: res.data
      })
    })
  },
  onShow: function () {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo != "") {
      db.collection('shoppingcart').where({
        _openid: userInfo._openid
      }).get().then(res => {
        var record = res.data
        var sum = 0
        for (let i = 0; i < record.length; i++) {
          sum = sum + record[i].num
        }
        app.globalData.goodnum = sum
        if (sum != 0) {
          wx.setTabBarBadge({
            index: 2,
            text: sum + ""
          })
        } else {
          wx.removeTabBarBadge({
            index: 2
          })
        }
      })
    }
  },

  selectclass: function (event) {
    var class_cur = this.data.class_cur
    var index = event.currentTarget.dataset.index
    if (class_cur != index) {
      db.collection('goods').where({
        classification: index
      }).get().then(res => {
        this.setData({
          goodinfo: res.data,
          class_cur: index
        })
      })
    }
  },

  addtoCart: function (event) {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo == "") {
      wx.navigateTo({
        url: '../auth/auth'
      })
    } else {
      var index = event.currentTarget.dataset.index
      var code = event.currentTarget.dataset.code
      var item = this.data.goodinfo[index]
      item.submitdate = db.serverDate()
      item.openid = userInfo.openid
      item.num = 1
      delete item._id
      db.collection('shoppingcart').where({
        _openid: userInfo._openid,
        code: code
      }).get().then(res => {
        var cart = res.data
        if (cart.length == 0) {
          db.collection('shoppingcart').add({
              data: item,
            })
            .then(res => {
              var sum = app.globalData.goodnum + 1
              app.globalData.goodnum = sum
              wx.setTabBarBadge({
                index: 2,
                text: sum + ""
              })
            })
        } else {
          db.collection('shoppingcart').doc(cart[0]._id).update({
            data: {
              num: _.inc(1)
            }
          }).then(res => {
            var sum = app.globalData.goodnum + 1
            app.globalData.goodnum = sum
            wx.setTabBarBadge({
              index: 2,
              text: sum + ""
            })
          })
        }
      })
    }
  }
})